package com.app.micaihu.ad.toutiao;


import android.content.Context;

import com.app.micaihu.bean.ad.NativeAd;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ScreenUtils;
import com.blankj.utilcode.util.Utils;
import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.TTAdManager;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTNativeExpressAd;

import java.util.LinkedList;
import java.util.List;

/**
 * 头条广告管理类
 *
 * @author linkai
 */
public class ToutiaoNativeAd {

    //请求广告的工具
    private TTAdNative mTTAdNative;
    private AdSlot adSlot;
    //缓存下来的广告（拉取下来了，但是还没有在前端展示）
    private final LinkedList<TTNativeExpressAd> nrAdList = new LinkedList<>();
    private final Object mLocker = new Object();
    //请求的广告位id
    private String mPosId;

    private NativeAd nativeAd;

    public ToutiaoNativeAd(NativeAd nativeAd) {
        if (nativeAd == null) {
            return;
        }
        this.nativeAd = nativeAd;
        mPosId = nativeAd.getAdId();
        //初始化请求广告
        initNativeAd();
    }


    /**
     * 初始化广告
     *
     */
    private void initNativeAd() {
        //feed广告请求类型参数
        AdSlot adSlot = getAdSlot();

        ToutiaoNativeRequest baiduReq = new ToutiaoNativeRequest(0,  mPosId, nrAdList, adSlot);
//        addbaiduReqCache(baiduReq);
        baiduReq.adRequest();

    }

    /**
     * 返回用户请求的信息
     *
     * @return
     */
    private AdSlot getAdSlot() {
        if (adSlot == null) {
//            int width = 0;
//            int height = 0;
//            if (TextUtils.equals(nativeAd.getStyle(), AdConfigManager.SHOW_BIG_IMG)) {
//                width = 690;
//                height = 388;
//            } else {
//                width = 228;
//                height = 150;
//            }
            //feed广告请求类型参数
            adSlot = new AdSlot.Builder()
                    .setCodeId(mPosId)
                    .setSupportDeepLink(true)
//                    .setImageAcceptedSize(width, height)
                    .setExpressViewAcceptedSize(ScreenUtils.getAppScreenWidth(), 0)
                    .setAdCount(3)//最多支持3个广告
                    .build();
        }

        return adSlot;
    }

    /**
     * 拉取广告
     */
    public synchronized void loadNativeAdList() {
        //feed广告请求类型参数
        AdSlot adSlot = getAdSlot();
        ToutiaoNativeRequest baiduReq = new ToutiaoNativeRequest(0,  mPosId, nrAdList, adSlot);
//        addbaiduReqCache(baiduReq);
        baiduReq.adRequest();
    }

    /**
     * 获取一个广告
     *
     * @return NativeResponse
     */
    public synchronized TTNativeExpressAd getNativeAd() {
        if (nrAdList.size() == 0) {
            loadNativeAdList();
            return null;
        }
        TTNativeExpressAd adret = nrAdList.removeFirst();
        //如果当前广告缓存集合里的存储的广告数量小于2,则拉取广告
        if (nrAdList.size() < 2) {
            loadNativeAdList();
        }

        return adret;
    }

    /**
     * 返回当前广告缓存集合的数量大小
     *
     * @return
     */
    public int getNativeAdSize() {
        synchronized (mLocker) {
            return nrAdList.size();
        }
    }

    /**
     * 单独加载一个广告
     *
     * @param context  独立上下文对象
     * @param adPosId  独立广告位id
     * @param callback 回调函数
     */
    public void loadOneAd(Context context, final String adPosId, final NativeAdLoadCallback callback) {
        if (callback == null) {
            return;
        }
        if (context == null || adPosId == null) {
            callback.onNativeAdLoad(null, false);
            return;
        }
        AdSlot adSlot = getAdSlot();

        if (mTTAdNative == null) {
            TTAdManager ttAdManager = TTAdManagerHolder.get();
            mTTAdNative = ttAdManager.createAdNative(Utils.getApp().getApplicationContext());
        }
//        HashMap<String, String> map = AdMapUtils.getPositionMap();
//        map.put(AdMapUtils.adPositionList + AdMapUtils.adRequestKey, adPosId);
//        MobclickAgentUtils.event(Config.EventId.toutiao_ad, map);
        mTTAdNative.loadNativeExpressAd(adSlot, new TTAdNative.NativeExpressAdListener() {
            @Override
            public void onError(int code, String message) {
//                HashMap<String, String> map = AdMapUtils.getPositionMap();
//                map.put(AdMapUtils.adPositionList + "onError", adPosId);
//                map.put(AdMapUtils.adPositionList + "errorMsg", message);
//                map.put(AdMapUtils.adPositionList + "errorCode", code + "");
//                MobclickAgentUtils.event(Config.EventId.toutiao_ad, map);
                LogUtils.e("toutiao", "id=" + adPosId + "  " + code, message);
                callback.onNativeAdLoad(null, false);
            }

            @Override
            public void onNativeExpressAdLoad(List<TTNativeExpressAd> list) {
//                HashMap<String, String> map = AdMapUtils.getPositionMap();
//                map.put(AdMapUtils.adPositionList + AdMapUtils.adSuccessKey, adPosId);
//                MobclickAgentUtils.event(Config.EventId.toutiao_ad, map);
                if (list != null) {
                    int size = list.size();
                    if (size > 0) {
                        for (int i = 0; i < size; i++) {
                            TTNativeExpressAd ttNativeExpressAd = list.get(i);
                            if (ttNativeExpressAd != null) {
                                ttNativeExpressAd.render();
                            }
                        }
                        TTNativeExpressAd ttNativeExpressAd = list.get(0);
                        if (ttNativeExpressAd != null) {
                            callback.onNativeAdLoad(ttNativeExpressAd, true);
                        }
                        nrAdList.addAll(list);
                    }

                }
            }
        });
    }

    public interface NativeAdLoadCallback {
        void onNativeAdLoad(TTNativeExpressAd ad, boolean success);
    }
}
